gameInfo = {
    roomId: null,
    thisUserId: null,
    thatUserId: null,
    isWhite: true,
}

//////////////////////////////////////////////////
// 设定界面显示相关操作
//////////////////////////////////////////////////


function setScreenText(me) {
    const screen = document.querySelector('#screen');
    // 添加动画效果
    screen.classList.add('strong');
    setTimeout(() => screen.classList.remove('strong'), 300);

    // 专业棋类术语提示
    const color1 = gameInfo.isWhite ? '白方' : '黑方';
    const color2 = gameInfo.isWhite ? '黑方' : '白方';
    screen.innerHTML = me
        ? `<span class="highlight">你的回合&nbsp${color1}行棋</span>`
        : `<span class="waiting">对手回合&nbsp${color2}思考中</span>`;

    // 同步更新页面标题
    document.title = me ? "【您的回合】五子棋" : "【对方回合】五子棋";
}

//////////////////////////////////////////////////
// 初始化 websocket
//////////////////////////////////////////////////
let websocketUrl = "ws://" + location.host + "/game";
let websocket = new WebSocket(websocketUrl);

websocket.onopen = function () {
    console.log("连接游戏房间成功")
}

websocket.onclose = function () {
    console.log("和服务器断开连接")
}

websocket.onerror = function () {
    console.log("服务器连接出现异常")
}

websocket.onbeforeunload = function () {
    websocket.close();
}

//处理服务器返回的响应数据
websocket.onmessage = function (event) {
    console.log("[handlerGameReady] " + event.data)
    let resp = JSON.parse(event.data);

    if (!resp.ok) {
        window.toast = showToast('连接游戏失败 reason: ' + resp.reason, 'error');
        location.assign('/game_hall.html');
        return;
    }

    if (resp.message == 'gameReady') {
        gameInfo.roomId = resp.roomId;
        gameInfo.thisUserId = resp.thisUserId;
        gameInfo.thatUserId = resp.thatUserId;
        gameInfo.isWhite = (resp.whiteUser == resp.thisUserId);

        //初始化棋盘
        initGame();
        //设置显示区域的内容
        setScreenText(gameInfo.isWhite);
    } else if (resp.message == 'repeatConnection') {
        window.toast = showToast('检测到游戏多开 请使用其他账号登录', 'error');
        setTimeout(() => {
            location.assign("/login.html");
        }, 1200);
    }
}

//////////////////////////////////////////////////
// 初始化一局游戏
//////////////////////////////////////////////////
function initGame() {
    // 是我下还是对方下. 根据服务器分配的先后手情况决定
    let me = gameInfo.isWhite;
    // 游戏是否结束
    let over = false;
    let chessBoard = [];
    //初始化chessBord数组(表示棋盘的数组)
    for (let i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }
    let chess = document.querySelector('#chess');
    let context = chess.getContext('2d');
    context.strokeStyle = "#BFBFBF";
    // 背景图片
    let logo = new Image();
    logo.src = "images/chessBack.png";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
    }

    // 绘制棋盘网格
    function initChessBoard() {
        const context = document.querySelector('#chess').getContext('2d');
        context.strokeStyle = "rgba(40, 40, 40, 0.85)";
        context.lineWidth = 1.8;
        context.shadowColor = "rgba(0, 0, 0, 0.3)";
        context.shadowBlur = 2;
        context.shadowOffsetY = 1;
        context.translate(0.5, 0.5);

        for (let i = 0; i < 15; i++) {
            context.beginPath();
            context.moveTo(15.5 + i * 30, 15.5);
            context.lineTo(15.5 + i * 30, 434.5);
            context.stroke();

            context.beginPath();
            context.moveTo(15.5, 15.5 + i * 30);
            context.lineTo(434.5, 15.5 + i * 30);
            context.stroke();
        }

        context.fillStyle = "rgba(80, 80, 80, 0.9)";
        context.beginPath();
        context.arc(225.5, 225.5, 3.5, 0, 2 * Math.PI);
        context.fill();
    }


    // 绘制一个棋子, me 为 true
    function oneStep(i, j, isWhite) {
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        if (!isWhite) {
            gradient.addColorStop(0, "#0A0A0A");
            gradient.addColorStop(1, "#636766");
        } else {
            gradient.addColorStop(0, "#D1D1D1");
            gradient.addColorStop(1, "#F9F9F9");
        }
        context.fillStyle = gradient;
        context.fill();
    }

    chess.onclick = function (e) {
        if (over) {
            return;
        }
        if (!me) {
            return;
        }
        let x = e.offsetX;
        let y = e.offsetY;
        // 注意, 横坐标是列, 纵坐标是行
        let col = Math.floor(x / 30);
        let row = Math.floor(y / 30);
        if (chessBoard[row][col] == 0) {
            //  发送坐标给服务器, 服务器要返回结果
            send(row, col);

            // oneStep(col, row, gameInfo.isWhite);
            // chessBoard[row][col] = 1;
        }
    }

    function send(row, col) {
        let req = {
            message: 'putChess',
            userId: gameInfo.thisUserId,
            row: row,
            col: col
        };

        websocket.send(JSON.stringify(req));
    }

    //上一个websocket.onmessage 主要是用来处理了游戏就绪响应
    //这个方法针对落子响应
    websocket.onmessage = function (event) {
        console.log("[handlerPutChess] " + event.data);

        let resp = JSON.parse(event.data);
        if (resp.message != 'putChess') {
            console.log("响应类型错误");
            window.toast = showToast('响应类型错误', 'error');
            return;
        }

        //先判定当前这个响应是谁落子
        if (resp.userId == gameInfo.thisUserId) {
            //自己落子,绘制棋子
            oneStep(resp.col, resp.row, gameInfo.isWhite);
        } else if (resp.userId == gameInfo.thatUserId) {
            //对手落子
            oneStep(resp.col, resp.row, !gameInfo.isWhite);
        } else {
            //响应错误,userID有问题
            console.log('[handlerPutChess] resp userId 错误!');
            window.toast = showToast('[handlerPutChess] resp userId 错误', 'error');
            return;
        }

        //给落子处设置为1
        chessBoard[resp.row][resp.col] = 1;

        //交换双方的落子伦次
        me = !me;
        setScreenText(me);

        //判定游戏是否结束
        let screenDiv = document.querySelector('#screen');
        if (resp.winner != 0 && resp.winner != -1) {
            if (resp.winner == gameInfo.thisUserId) {
                screenDiv.innerHTML = '<span class="victory">对局胜利</span>';
            } else if (resp.winner == gameInfo.thatUserId) {
                screenDiv.innerHTML = '<span class="defeat">对局失败</span>';
            } else {
                window.toast = showToast('winner 字段错误' + resp.winner, 'error');
            }

            //返回按钮
            let backBtn = document.createElement('button');
            backBtn.className = 'return-btn';
            backBtn.innerHTML = '回到大厅';
            backBtn.onclick = function () {
                location.replace('/game_hall.html');
            }
            let fatherDiv = document.querySelector('.container>div');
            fatherDiv.appendChild(backBtn);

        } else if (resp.winner == -1) {
            screenDiv.innerHTML = '和棋 旗鼓相当的对手';

            //返回按钮
            let backBtn = document.createElement('button');
            backBtn.className = 'return-btn';
            backBtn.innerHTML = '回到大厅';
            backBtn.onclick = function () {
                location.replace('/game_hall.html');
            }
            let fatherDiv = document.querySelector('.container>div');
            fatherDiv.appendChild(backBtn);
        }
    }
}


